package org.dromara.creditcard.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.creditcard.domain.CreditBillMonthRecord;
import org.dromara.creditcard.domain.CreditCard;
import org.dromara.creditcard.service.ICreditBillMonthRecordService;
import org.dromara.creditcard.service.ICreditCardService;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.system.domain.SysRole;
import org.dromara.system.service.ISysRoleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 信用卡列
 *
 * @author Mr.Zhou
 * @date 2023-11-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/credit/card")
public class CreditCardController extends BaseController {

    private final ICreditCardService creditCardService;

    private final ISysRoleService sysRoleService;

    private final ICreditBillMonthRecordService billMonthRecordService;

    /**
     * 查询信用卡列表
     */
    @SaCheckPermission("credit:card:list")
    @GetMapping("/list")
    public TableDataInfo<CreditCard> list(CreditCard creditCard, PageQuery pageQuery) {

        Integer agentId = null;
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysRole sysRole = sysRoleService.selectRoleByUserId(loginUser.getUserId());
        if(sysRole != null){
            if(sysRole.getRoleKey().equals("agent") || sysRole.getRoleKey().equals("business")) {
                agentId = loginUser.getAgentId();
            }
        }

        QueryWrapper<CreditCard> qw = new QueryWrapper<>();
        if(agentId != null){
            qw.eq("agent_id", agentId);
        }else{
            if(creditCard.getAgentId() != null){
                qw.eq("agent_id", creditCard.getAgentId());
            }
        }
        if(creditCard.getHolderId() != null){
            qw.eq("holder_id", creditCard.getHolderId());
        }
        if(StrUtil.isNotEmpty(creditCard.getCardNum())){
            qw.like("card_num", creditCard.getCardNum());
        }
        qw.orderByDesc("id");

        TableDataInfo<CreditCard> td = PageUtils.buildDataInfo(creditCardService.page(PageUtils.buildPage(),qw));
        List<CreditCard> list = td.getRows();
        return td;
    }

    /**
     * 导出信用卡列表
     */
    @SaCheckPermission("credit:card:export")
    @Log(title = "信用卡列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CreditCard creditCard, HttpServletResponse response) {
        QueryWrapper<CreditCard> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(creditCard.getCardNum())){
            qw.like("card_num", creditCard.getCardNum());
        }
        List<CreditCard> list = creditCardService.list(qw);
        ExcelUtil.exportExcel(list, "信用卡列表", CreditCard.class, response);
    }

    /**
     * 获取信用卡列表详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("credit:card:query")
    @GetMapping("/{id}")
    public R<CreditCard> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(creditCardService.getById(id));
    }

    /**
     * 新增信用卡列表
     */
    @SaCheckPermission("credit:card:add")
    @Log(title = "信用卡列表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CreditCard creditCard) {

        QueryWrapper<CreditCard> qw = new QueryWrapper<>();
        qw.eq("card_num",creditCard.getCardNum());
        qw.last("limit 1");
        long cardCount = creditCardService.count(qw);
        if(cardCount > 0){
            return R.fail("该卡片已存在");
        }

        creditCard.setCreateTime(new Date());
        LoginUser loginUser = LoginHelper.getLoginUser();
        creditCard.setAgentId(loginUser.getAgentId());
        return toAjax(creditCardService.save(creditCard));
    }

    /**
     * 修改信用卡列表
     */
    @SaCheckPermission("credit:card:edit")
    @Log(title = "信用卡列表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CreditCard creditCard) {
        return toAjax(creditCardService.updateById(creditCard));
    }

    /**
     * 删除信用卡列表
     *
     * @param ids 主键串
     */
    @SaCheckPermission("credit:card:remove")
    @Log(title = "信用卡列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(creditCardService.removeByIds(Arrays.asList(ids)));
    }
}
